package com.chenju.javastatic.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class EasyJsonUtils {

    public static String mapToJson(Map<String, Object> map) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> jsonToMap(String jsonString){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    public static String listToJson(List<String> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> jsonToList(String jsonString) {
        if ("".equals(jsonString)){
            return null;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonString, new TypeReference<List<String>>() {});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
